import type { AxiosResponse } from 'axios';
import { BACKEND_ERROR_CODE, createFlatRequest } from '@sa/axios';
import { useAuthStore } from '@/store/modules/auth';
import { getServiceBaseURL } from '@/utils/service';
import { getAuthorization, handleExpiredRequest, showErrorMsg } from './shared';
import type { RequestInstanceState } from './type';

const isHttpProxy = import.meta.env.DEV && import.meta.env.VITE_HTTP_PROXY === 'Y';
const { baseURL } = getServiceBaseURL(import.meta.env, isHttpProxy);

export const request = createFlatRequest<App.Service.Response, RequestInstanceState>(
  { baseURL },
  {
    async onRequest(config) {
      const Authorization = getAuthorization();
      Object.assign(config.headers, { Authorization });
      return config;
    },
    isBackendSuccess(response) {
      // 当后端响应码为 "0"（默认值）时，表示请求成功
      // 如果你想修改这个逻辑，可以在 .env 文件中修改 VITE_SERVICE_SUCCESS_CODE 的值
      return String(response.data.code) === import.meta.env.VITE_SERVICE_SUCCESS_CODE;
    },
    async onBackendFail(response, instance) {
      const authStore = useAuthStore();
      const responseCode = String(response.data.code);

      function handleLogout() {
        authStore.logout();
      }

      // function logoutAndCleanup() {
      //   handleLogout();
      //   window.removeEventListener('beforeunload', handleLogout);

      //   request.state.errMsgStack = request.state.errMsgStack.filter(msg => msg !== response.data.message);
      // }

      const expiredTokenCodes = import.meta.env.VITE_SERVICE_EXPIRED_TOKEN_CODES?.split(',') || [];

      // 当后端响应代码在 logoutCodes 中时，意味着用户将被登出并重定向到登录页面
      const logoutCodes = import.meta.env.VITE_SERVICE_LOGOUT_CODES?.split(',') || [];
      // 当用户没有 token 时，意味着用户将被登出并重定向到登录页面
      if (logoutCodes.includes(responseCode)) {
        handleLogout();
        return null;
      }
      /** 刷新令牌过期后，清除 token 相关 sessionStorage 用户将被登出并重定向到登录页面 */
      const expiredRefreshTokenCodes = import.meta.env.VITE_SERVICE_EXPIRED_REFRESHTOKEN_CODES;
      if (responseCode === expiredRefreshTokenCodes) {
        authStore.resetTokenStg();
        handleLogout();
        return null;
      }

      // 后端服务的登出代码，当接收到该代码时，用户将通过显示一个模态框（modal）被登出
      // const modalLogoutCodes = import.meta.env.VITE_SERVICE_MODAL_LOGOUT_CODES?.split(',') || [];
      // if (modalLogoutCodes.includes(responseCode) && !request.state.errMsgStack?.includes(response.data.message)) {
      //   request.state.errMsgStack = [...(request.state.errMsgStack || []), response.data.message];

      //   // prevent the user from refreshing the page
      //   window.addEventListener('beforeunload', handleLogout);

      //   window.$dialog?.error({
      //     title: '错误',
      //     content: response.data.message,
      //     positiveText: '确认',
      //     maskClosable: false,
      //     closeOnEsc: false,
      //     onPositiveClick() {
      //       logoutAndCleanup();
      //     },
      //     onClose() {
      //       logoutAndCleanup();
      //     }
      //   });

      //   return null;
      // }

      // 当后台响应码在 expiredTokenCodes 中时，表示令牌已过期，需要刷新令牌
      // API refreshToken 不能返回 expiredTokenCodes 中的错误码，否则会形成死循环，应返回 logoutCodes 或 modalLogoutCodes
      if (expiredTokenCodes.includes(responseCode)) {
        const success = await handleExpiredRequest(request.state);
        if (success) {
          const Authorization = getAuthorization();
          Object.assign(response.config.headers, { Authorization });

          return instance.request(response.config) as Promise<AxiosResponse>;
        }
      }

      return null;
    },
    transformBackendResponse(response) {
      return response.data.data;
    },
    async onError(error) {
      if (error.stack?.includes('timeout')) {
        showErrorMsg(request.state, '请求超时，请重试！');
        return;
      }

      // const authStore = useAuthStore();
      // function handleLogout() {
      //   authStore.logout();
      // }

      let message = error.message;
      // const backendErrorCode = String(error.response?.data?.code || '');

      // 获取后端错误信息和代码
      if (error.code === BACKEND_ERROR_CODE) {
        message = error.response?.data?.msg || message;
      }

      // 错误信息会显示在模态框中
      // const modalLogoutCodes = import.meta.env.VITE_SERVICE_MODAL_LOGOUT_CODES?.split(',') || [];
      // if (modalLogoutCodes.includes(backendErrorCode)) {
      //   return;
      // }

      showErrorMsg(request.state, error.response?.data?.msg || message);
    }
  }
);
